from flask import Blueprint, g, jsonify
from flask_restful import Resource, Api, reqparse, fields, abort, marshal

from apps.models.moey_model import WalletMoney
from apps.utils.decorator import login_required
from exts import db

chongzhi_bp = Blueprint('chongzhi', __name__, url_prefix='/chongzhi')

api = Api(chongzhi_bp)

parser = reqparse.RequestParser()
parser.add_argument('money_localtion', type=str, required=True, help='必须输入充值地址')
parser.add_argument('moneyB_count', type=float, required=True, help='必须输入要充值的数量')

chongzhi_fileds = {
    # 货币A
    'moneyA': fields.Float,
    # 货币B
    'moneyB': fields.Float,
}


class ChongZhiResource(Resource):
    @login_required
    def post(self):
        user = g.user
        if user:
            # 20A=1B
            args = parser.parse_args()
            di_zhi = args.get("money_localtion")
            moneyB_count = args.get("moneyB_count")
            if not di_zhi:
                abort(400, msg='请输入充值地址')
            money = WalletMoney.query.filter(WalletMoney.money_localtion == di_zhi).first()
            if money:

                money.moneyB += moneyB_count
                db.session.add(money)
                db.session.commit()

                data = {
                    'status': 200,
                    'msg': '充值成功',
                    'money': marshal(money, chongzhi_fileds)
                }
                return jsonify(data)
            else:
                abort(400, msg='地址输入有误')


api.add_resource(ChongZhiResource, '/')
